/**
 * jQuery插件：提示层
 * 
 * @author  Karson
 * @url     http://blog.iplaybus.com
 * @name    jquery.dialog.js
 * @since   2013-5-29 17:20:04
 */
var tshow = 0;
var ti = {};
var dialog = {
    setting: {
        id: 'dialog',
        title: '标题',
        type: 'content',
        content: '',
        width: 400,
        height: 300,
        fixed: false,
        refix: true,
        x: "center",
        y: "middle",
        time: 0,
        lock: false,
        drag: true,
        follow: null,
        remove: false,
        style: '',
        btnok: '确认',
        btncancel: '取消',
        ok: function() {
        },
        cancel: function() {
        },
        close: function() {
        },
        mousemove: function() {
        }
    },
    show: function(options) {   //显示
        dialog.setting.id = 'dialog';
        var opts = $.extend({}, dialog.setting, options);
        if (opts.id == "dialog") {
            opts.id = "dialog" + Math.floor(Math.random() * 10000 + 1);
        }
        dialog.setting.id = opts.id;
        eval("typeof ti." + opts.id + " == 'undefined' ? 0 : clearTimeout(ti." + opts.id + ");");
        if (opts.remove) {
            $(".dialog_mask,.dialog_box").remove();
        }
        //获取层尺寸
        var _ow = dialog.strip_px(opts.width);
        var _oh = dialog.strip_px(opts.height);
        if (opts.type == 'iframe' || opts.type == 'frame') {
            opts.content = "<iframe title='" + opts.title + "' id='frame_" + opts.id + "' src='" + opts.content + "' scrolling='yes' frameborder='0' style='height:100%;width:100%'></iframe>";
        } else if (opts.type == 'img' || opts.type == 'image') {
            opts.content = "<img src='" + opts.content + "' title='" + opts.title + "' />";
        } else if (opts.type == 'flash' || opts.type == 'swf') {
            var ftemp = '';
            ftemp += '<object id="flash_' + opts.id + '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="100%" height="100%">';
            ftemp += '<param name="movie" value="' + opts.content + '"><param name="quality" value="high"><param name=wmode value="opaque">';
            ftemp += '<embed src="' + opts.content + '" wmode="opaque" quality="high" width="100%" height="100%" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
            opts.content = ftemp;
        }
        move = opts.drag ? 'style="cursor:move;"' : '';
        var newdialog = $("#" + opts.id);
        var ie6 = $.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent);
        var zindex = 9998;
        var html = '';
        html += opts.lock ? '<div class="dialog_mask" id="mask_' + opts.id + '"></div>' : '';
        html += '<div class="dialog_box ' + opts.style + '" id="' + opts.id + '" style="display:none;width:' + _ow + 'px;height:' + _oh + 'px">';
        html += '    <div class="dialog_shadow" style="width:' + _ow + 'px;height:' + _oh + 'px"></div>';
        html += '    <div class="dialog_layer">';
        html += '        <div class="dialog_title" id="title_' + opts.id + '" ' + move + '>' + opts.title + '</div>';
        html += '        <div class="dialog_close" id="close_' + opts.id + '" title="">×</div>';
        html += '        <div class="dialog_content" id="content_' + opts.id + '">';
        html += '             ' + opts.content;
        html += '        </div>';
        html += '        <div class="dialog_button" id="button_' + opts.id + '"><input type="button" class="dialog_ok bluebtn" value="' + opts.btnok + '" id="ok_' + opts.id + '" /> <input type="button" class="dialog_cancel greenbtn" value="' + opts.btncancel + '" id="cancel_' + opts.id + '" /></div>';
        html += '    </div>';
        html += ie6 ? '<!--[if IE 6]><iframe id="' + opts.id + 'ie6_select_mask" class="ie6_select_mask" style="width:' + _ow + 'px;height:' + _oh + 'px" src="javascript:;"></iframe><![endif]-->' : '';
        html += '</div>';

        //判断对象是否已经存在
        if (newdialog.size() == 0) {
            $("body").prepend($(html));
        } else {
            $("#mask_" + opts.id).remove();
            $("#" + opts.id).replaceWith(html);
        }
        newdialog = $("#" + opts.id);
        //获取客户端屏幕尺寸
        var _cw = document.body.clientWidth;
        var _ch = document.body.clientHeight;
        //获取弹出层尺寸
        var _dw = newdialog.width();
        var _dh = newdialog.height();
        //_ch = document.documentElement.scrollHeight;
        //获取可视窗口尺寸
        var _ww = $(window).width();
        var _wh = $(window).height();
        if (opts.follow) {
            //当为跟随对象时强制转换fixed为false
            opts.fixed = false;
            m = $(opts.follow)[0];
            l = dialog.position(m);
            x = l.left;
            y = l.top + l.height;
            fx = _cw - _dw;
            fy = l.top - _dh;
            x = x > fx ? fx - 35 : x;
            y = (fy > _dh && y > fy) ? fy : y;
        } else {
            x = opts.x;
            y = opts.y;
            if (x == 'left') {
                x = 0;
            } else if (x == "center") {
                x = _ww / 2 - _dw / 2;
            } else if (x == 'right') {
                x = _ww - _dw - 2;
            } else {
                x = x;
            }
            var t = -1;
            if (y == 'top') {
                t = 0;
                y = 0;
            } else if (y == "middle") {
                t = _wh / 2 - _dh / 2;
                y = t;
            } else if (y == 'bottom') {
                t = -1;
                y = _wh - _dh - 2;
            } else {
                t = y;
                y = y;
            }
            x = dialog.strip_px(x);
            y = dialog.strip_px(y);
        }
        position = opts.fixed ? "fixed" : "absolute";
        newdialog.css({
            left: x + 'px',
            top: y + 'px',
            position: position,
            "z-index": zindex
        });
        $('close_' + opts.id).css("z-index", zindex + 1);
        if (ie6 && position == 'fixed') {
            if (t >= 0) {
                newdialog.attr("style", "top:expression(documentElement.scrollTop+" + t + ");");
            } else {
                newdialog.attr("style", "top:expression(documentElement.scrollTop+documentElement.clientHeight-this.offsetHeight);");
            }
            newdialog.css({
                position: 'absolute',
                left: x + "px",
                width: _ow + "px"
            });
            //防ie6跳动
            $("body").css("background-attachment", "fixed").css("background-image", "url(/images/n1othing.txt)");
        }
        var _mh = $(document.body)[0].offsetHeight < _wh ? _wh : $(document.body)[0].offsetHeight;
        $(".dialog_mask").height(_mh);
        dialog.repair_zindex(newdialog);
        newdialog.show();
        $("#content_" + opts.id + ",#frame_" + opts.id).height(_oh - $('#title_' + opts.id)[0].offsetHeight - $('#button_' + opts.id)[0].offsetHeight - 10);
        //$("#flash_"+opts.id).attr("height",$("#content_"+opts.id).height());
        //给确定按钮加上回调事件
        $("#ok_" + opts.id).bind("click", function() {
            $.dialog.close(opts.id, function() {
                opts.ok(newdialog);
            });
        });
        //给取消按钮加上关闭窗口事件和回调事件
        $("#cancel_" + opts.id).bind("click", function() {
            $.dialog.close(opts.id, function() {
                opts.cancel(newdialog);
            });
        });
        //给关闭按钮加上关闭窗口事件和回调事件
        $("#close_" + opts.id).bind("click", function() {
            $.dialog.close(opts.id, function() {
                opts.close(newdialog);
            });
        });
        if (opts.drag) {  //拖动
            dialog.drag(newdialog, $("#" + opts.id + " div.dialog_title"), opts.mousemove);
        }
        if (opts.time > 0) {    //自动关闭
            var t = setTimeout(function() {
                dialog.close(opts.id, function() {
                    opts.close(newdialog)
                });
            }, opts.time);
            eval("ti." + opts.id + "=" + t + ";");
        }
        ;
        if (opts.refix && opts.follow == null && (opts.x == 'center' || opts.y == 'middle')) {
            $(window).resize(function() {
                newdialog.stop().animate({
                    left: $(window).width() / 2 - _dw / 2,
                    top: $(window).height() / 2 - _dh / 2
                }, 300);
            });
        }
        return newdialog;
    },
    update: function(id, content, callback) { //更新
        id = id != undefined ? id : dialog.setting.id;
        $('#' + id + ' .dialog_body').html(content);
        if (callback != undefined) {
            callback($('#' + id));
        }
    },
    close: function(id, callback) {  //关闭
        id = id != undefined ? id : dialog.setting.id;
        eval("typeof ti." + id + " == 'undefined' ? 0 : clearTimeout(ti." + id + ");");
        $('#' + id + ',#mask_' + id).hide().remove();
        if (callback != undefined) {
            callback($('#' + id));
        }
    },
    strip_px: function(u) { //处理px单位
        u = "" + u + "";
        return parseInt(u.split("p")[0]);
    },
    repair_zindex: function(o) {
        if (o.css('z-index') != 9999) {
            var d;
            $(".dialog_box").each(function() {
                d = $(this);
                d.css('z-index', d.css('z-index') - 1);
            });
            o.css('z-index', 9999);
        }
    },
    position: function(e) {
        if (e == undefined) {
            return {
                top: 0,
                left: 0,
                width: 0,
                height: 0
            };
        } else {
            var oTop = e.offsetTop;
            var oLeft = e.offsetLeft;
            var oWidth = e.offsetWidth;
            var oHeight = e.offsetHeight;
            while (e = e.offsetParent) {
                oTop += e.offsetTop;
                oLeft += e.offsetLeft;
            }
            return {
                top: oTop,
                left: oLeft,
                width: oWidth,
                height: oHeight
            }
        }
    },
    drag: function(target, trigger, callback) {
        var d = $(document);
        trigger.mousedown(function(e) {
            var e = e || window.event;
            //重置z-index的值
            dialog.repair_zindex(target);
            var positionX = e.clientX - target.offset().left;
            var positionY = e.clientY - target.offset().top;
            d.mousemove(function(e) {
                var left = e.clientX - positionX;
                var top = e.clientY - positionY;
                //防止头部消息
                //left = left < 0 ? 0 : left;
                //top = top < 0 ? 0 : top;
                target.css({
                    position: 'absolute',
                    left: left,
                    top: top
                });
                if (callback != undefined)
                    callback(target);
            });
            d.mouseup(function() {
                d.unbind('mousemove');
                d.unbind('mouseup');
                this.releaseCapture && this.releaseCapture();
            });
            this.setCapture && this.setCapture();
            return false;
        });
    }
};

jQuery.dialog = function(setting) {
    return dialog.show(setting);
}
jQuery.dialog.close = function(id, callback) {
    // 如果自动循环被打开，则在关闭窗体时将其关闭(以免关闭视频播放后出现JS错误提示)
    //if(tshow!=undefined){clearInterval(tshow)}
    return dialog.close(id, callback);
}
jQuery.dialog.update = function(id, content, callback) {
    return dialog.update(id, content, callback);
}
jQuery.dialog.alert = function(content, type, callback) {
    type = type == undefined ? 'help' : type;
    dialog.show({
        id: 'alertid',
        title: '温馨提示',
        content: "<table class='dialog_table' border='0' cellspacing='0' cellpadding='0'><tr><td><img src='" + SG.config.res_url + "/images/tips/" + type + ".gif' class='dialog_img'></td><td>" + content + "</td></tr></table>",
        fixed: true,
        time: 3000,
        height: '160',
        remove: true,
        lock: true,
        style: 'no_button',
        close: callback
    });
}
jQuery.dialog.confirm = function(content, type, okcallback, cancelcallback, closecallback) {
    type = type == undefined ? 'ask' : type;
    dialog.show({
        id: 'confirmid',
        title: '温馨提示',
        content: "<table class='dialog_table' border='0' cellspacing='0' cellpadding='0'><tr><td><img src='" + SG.config.res_url + "/images/tips/" + type + ".gif' class='dialog_img'></td><td>" + content + "</td></tr></table>",
        height: '190',
        fixed: true,
        remove: true,
        lock: true,
        style: '',
        ok: okcallback,
        cancel: cancelcallback,
        close: closecallback
    });
}